package cn.cmdr.controller;

import cn.cmdr.pojo.*;
import cn.cmdr.service.*;
import cn.cmdr.vo.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/sys/com")
public class ComController {
    @Resource
    private ComService comService;
    @Resource
    private SortService sortService;
    @Resource
    private BrandService brandService;
    @Resource
    private RecoveryService recoveryService;
    @Resource
    private JournalService journalService;

    @GetMapping("/comList")
    public ModelAndView getComList(String id){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("sys/comsee");
        Commodity commodity = comService.getComById(Integer.parseInt(id));
        Sort sort = sortService.getSort(commodity.getProductCategoryId());
        Brand brand = brandService.getBrand(commodity.getBrandId());
        modelAndView.addObject("sort",sort);
        modelAndView.addObject("brand",brand);
        modelAndView.addObject("commodity",commodity);
        return modelAndView;
    }
    @PostMapping("/list/{pageSize}/{pageNo}")
    public ResultVo getList(@PathVariable Integer pageSize, @PathVariable Integer pageNo, @RequestBody ComVo comVo){
        return ResultVo.sucess(comService.getPageComList(pageNo,pageSize,comVo));
    }
    @GetMapping("/stockList")
    public ModelAndView getstockList(String commodityid){
        List<Stock> list = comService.getStockByComId(Integer.parseInt(commodityid));
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("sys/comStock");
        modelAndView.addObject(list);
        return modelAndView;
    }

    @PostMapping("/edit")
    public ResultVo getComById(String id){
        return ResultVo.sucess(comService.getComById(Integer.parseInt(id)));
    }



   /* @PostMapping("/update")
    @RequiresPermissions("com:update")
    public ModelAndView update(@RequestBody Stock stock){
        ModelAndView modelAndView = new ModelAndView();
        try {
            comService.stockUpdate(stock);
            modelAndView.setViewName("sys/com");
            modelAndView.addObject("修改成功");
//            comService.getCom(stock.getCommodityId());
//            Journal journal = new Journal();
//            journal.setStaffId(((Staff) SecurityUtils.getSubject().getPrincipal()).getId());
//            journal.setUpDate(new Date());
//            journal.setUpContent("修改品牌:"+stock.);
//            journal.setMenuId(2);
//            journalService.add(journal);
            return modelAndView;
        }catch (Exception e){
            modelAndView.addObject("修改失败");
            return modelAndView;  //包含了打印错误日志
        }
    }*/
    @PostMapping("/update2")
    @RequiresPermissions("com:update")
    public ResultVo update2(@RequestBody Commodity commodity){
        try {
//            if(commodity.getPublishStatus()==0){
//                commodity.setPublishStatus(1);
//            }else if(commodity.getPublishStatus()==1){
//                commodity.setPublishStatus(0);
//            }
            comService.comUpdate(commodity);
            Journal journal = new Journal();
            journal.setStaffId(((Staff) SecurityUtils.getSubject().getPrincipal()).getId());
            journal.setUpDate(new Date());
            journal.setUpContent("修改商品:"+commodity.getName());
            journal.setMenuId(1);
            journalService.add(journal);
            return ResultVo.sucess("状态修改成功");
        }catch (Exception e){
            return ResultVo.fail("状态修改失败",e);  //包含了打印错误日志
        }
    }
    /*@PostMapping("/update3")
    @RequiresPermissions("com:update")
    public ModelAndView update3(@RequestBody Commodity commodity){
        ModelAndView modelAndView = new ModelAndView();
        try {
            comService.comUpdate(commodity);
            modelAndView.setViewName("sys/com");
            modelAndView.addObject("修改成功");
            return modelAndView;
        }catch (Exception e){
            modelAndView.addObject("修改失败");
            return modelAndView;  //包含了打印错误日志
        }
    }*/
    @PostMapping("/update4")
    @RequiresPermissions("com:update")
    public ResultVo update4(@RequestBody Commodity commodity){
        try {
            if(commodity.getPublishStatus()==0){
                commodity.setPublishStatus(1);
            }else if(commodity.getPublishStatus()==1){
                commodity.setPublishStatus(0);
            }
            comService.comUpdate(commodity);

            Journal journal = new Journal();
            journal.setStaffId(((Staff) SecurityUtils.getSubject().getPrincipal()).getId());
            journal.setUpDate(new Date());
            journal.setUpContent("修改商品上架状态:"+commodity.getName());
            journal.setMenuId(1);
            journalService.add(journal);

            return ResultVo.sucess("状态修改成功");
        }catch (Exception e){
            return ResultVo.fail("状态修改失败",e);  //包含了打印错误日志
        }
    }
    @PostMapping("/add")
    @RequiresPermissions("com:add")
    public ResultVo add(@RequestBody CsVo csVo,HttpSession session) {
        ModelAndView modelAndView = new ModelAndView();
        try {
            Subject subject = SecurityUtils.getSubject();
            Staff staff = (Staff) subject.getPrincipal();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            int random=(int)(Math.random()*10);
            String sn = sdf.format(new Date())+random;
            Commodity c = csVo.getCommodity();
            c.setProductSn(sn);
            c.setStaffId(staff.getId());
            comService.add(c);
            Journal journal = new Journal();
            journal.setStaffId(((Staff) SecurityUtils.getSubject().getPrincipal()).getId());
            journal.setUpDate(new Date());
            journal.setUpContent("添加商品:"+c.getName());
            journal.setMenuId(1);
            journalService.add(journal);
            Commodity commodity = comService.getc(c);
            List<Stock> stocks = csVo.getStocks();
            for (Stock stock:stocks){
                stock.setCommodityId(commodity.getId());
                comService.sAdd(stock);
            }
            Journal journal2 = new Journal();
            journal2.setStaffId(((Staff) SecurityUtils.getSubject().getPrincipal()).getId());
            journal2.setUpDate(new Date());
            journal2.setUpContent("添加库存:"+commodity.getName());
            journal2.setMenuId(10);
            journalService.add(journal2);
            return ResultVo.sucess("添加成功");
        } catch (Exception e) {

            return ResultVo.fail("添加失败",e);  //包含了打印错误日志
        }
    }
    @GetMapping("/comadd")
    public ModelAndView comadd(){
        return new ModelAndView("sys/comadd");
    }

    @PostMapping("/upload")
    public ResultVo upload(MultipartFile attach, HttpServletRequest request){
        ServletContext serviceContext = request.getServletContext();
        String realPath = serviceContext.getRealPath("img");
        File floader = new File(realPath);
        if(!floader.exists()){
            floader.mkdir();//如果没有这个文件夹就会创建一个文件夹
        }
        String original = attach.getOriginalFilename();//文件原始名字
        int index = original.lastIndexOf(".");
        String suffix = original.substring(index);//.jpg
        String newFileName = UUID.randomUUID().toString().replace("-","")+suffix;//文件新名字
        File file = new File(realPath,newFileName);
        try {
            attach.transferTo(file);

        }catch (IOException e){
            e.printStackTrace();
        }
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("attachPath","img/"+newFileName);
        return ResultVo.sucess(map);
    }

    @GetMapping("/exa")
    @RequiresPermissions("com:examine")
    public ModelAndView exa(String id){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/sys/examine");
        modelAndView.addObject("comexa",comService.getCom(Integer.parseInt(id)));
        return modelAndView;
    }

    @GetMapping("/doexa")
    @RequiresPermissions("com:examine")
    public ModelAndView doexa(String id,String verifyStatus){
        Commodity commodity = new Commodity();
        commodity = comService.getComById(Integer.parseInt(id));
//        commodity.setId(Integer.parseInt(id));
        commodity.setVerifyStatus(Integer.parseInt(verifyStatus));
        comService.update(commodity);
        Journal journal = new Journal();
        journal.setStaffId(((Staff) SecurityUtils.getSubject().getPrincipal()).getId());
        journal.setUpDate(new Date());
        journal.setUpContent("审核商品:"+commodity.getName());
        journal.setMenuId(1);
        journalService.add(journal);
        return new ModelAndView("/sys/com");
    }
    @GetMapping("/delete")
    @RequiresPermissions("com:del")
    public ResultVo delete(Integer id){
        try {
            Commodity commodity = new Commodity();
            commodity = comService.getComById(id);
            commodity.setDeleteStatus(1);
            comService.update(commodity);
            Journal journal = new Journal();
            journal.setStaffId(((Staff) SecurityUtils.getSubject().getPrincipal()).getId());
            journal.setUpDate(new Date());
            journal.setUpContent("删除商品:"+commodity.getName());
            journal.setMenuId(1);
            journalService.add(journal);
            return ResultVo.sucess("删除成功");
        }catch (Exception e){
            return ResultVo.fail("删除失败",e);  //包含了打印错误日志
        }
    }

    @PostMapping("/del")
    public ResultVo del(@RequestBody CsVo csVo){
        List list = csVo.getStocks();
        Stock stock = csVo.getStock();
        list.removeIf(s -> stock.equals(s));

        return ResultVo.sucess(list);
    }
    @PostMapping("/sk")
    @RequiresPermissions("com:update")
    public ResultVo getSk(@RequestBody Stock stock){

        List list = comService.getSk(stock);
        return ResultVo.sucess(list,list.size());
    }
    @PostMapping("/skupdate")
    @RequiresPermissions("com:update")
    public ResultVo skUpdate(@RequestBody Stock stock){
        try {
            comService.stockUpdate(stock);
            Commodity commodity = comService.getComById(stock.getCommodityId());
            Journal journal = new Journal();
            journal.setStaffId(((Staff) SecurityUtils.getSubject().getPrincipal()).getId());
            journal.setUpDate(new Date());
            journal.setUpContent("修改库存:"+commodity.getName());
            journal.setMenuId(10);
            journalService.add(journal);
            return ResultVo.sucess("修改成功");
        }catch (Exception e){
            return ResultVo.fail("修改失败",e);
        }
    }


    @PostMapping("/aShua")
    public ResultVo aShua(@RequestBody StockVo stockVo){
        List list = new ArrayList();
        String [] stockColor = stockVo.getStockColor();
        String [] stockBranch = stockVo.getStockBranch();
        for (int i = 0;i<stockColor.length;i++){
            for (int y=0;y<stockBranch.length;y++){
                Stock stock = new Stock();
                stock.setStockColor(stockColor[i]);
                stock.setStockBranch(stockBranch[y]);
                list.add(stock);
            }
        }
        return ResultVo.sucess(list,list.size());
    }

    @PostMapping("/kcadd")
    public ResultVo kcadd(@RequestBody kcVo kcVo){
        try {
            List<Stock> stocks = kcVo.getStocks();
            Integer id = kcVo.getId();
            for(Stock stock :stocks){
                stock.setCommodityId(id);
                comService.sAdd(stock);
            }
            Commodity commodity = comService.getComById(id);
            Journal journal = new Journal();
            journal.setStaffId(((Staff) SecurityUtils.getSubject().getPrincipal()).getId());
            journal.setUpDate(new Date());
            journal.setUpContent("添加库存:"+commodity.getName());
            journal.setMenuId(10);
            journalService.add(journal);
            return ResultVo.sucess("添加成功");
        }catch (Exception e){
            return ResultVo.fail("添加失败",e);
        }
    }
    @GetMapping("/recovery")
    public ModelAndView recovery(){
        return new ModelAndView("sys/comrecovery");
    }


    @PostMapping("/list2/{pageSize}/{pageNo}")
    public ResultVo getList2(@PathVariable Integer pageSize, @PathVariable Integer pageNo, @RequestBody ComVo comVo){
        return ResultVo.sucess(recoveryService.getPageComList(pageNo,pageSize,comVo));
    }
    @GetMapping("/del")
    public ResultVo del(Integer id){
        try {
            comService.delete(id);
            return ResultVo.sucess("删除成功");
        }catch (Exception e){
            return ResultVo.fail("删除失败",e);  //包含了打印错误日志
        }
    }
    @GetMapping("/hui")
    public ResultVo hui(Integer id){
        try {
            Commodity commodity = new Commodity();
            commodity = comService.getComById(id);
            commodity.setDeleteStatus(0);
            commodity.setPublishStatus(0);
            commodity.setVerifyStatus(0);
            comService.update(commodity);
            Journal journal = new Journal();
            journal.setStaffId(((Staff) SecurityUtils.getSubject().getPrincipal()).getId());
            journal.setUpDate(new Date());
            journal.setUpContent("恢复商品:"+commodity.getName());
            journal.setMenuId(1);
            journalService.add(journal);
            return ResultVo.sucess("恢复成功");
        }catch (Exception e){
            return ResultVo.fail("恢复失败",e);  //包含了打印错误日志
        }
    }
    @GetMapping("/delkc")
    public ResultVo delkc(Integer id){
        try {
            Stock stock = comService.getst(id);
            System.out.println(stock.getCommodityId());
            Commodity commodity = comService.getComById(stock.getCommodityId());
            Journal journal = new Journal();
            journal.setStaffId(((Staff) SecurityUtils.getSubject().getPrincipal()).getId());
            journal.setUpDate(new Date());
            journal.setUpContent("删除库存:"+commodity.getName());
            journal.setMenuId(10);
            journalService.add(journal);
            comService.delestock(id);
            return ResultVo.sucess("删除成功");
        }catch (Exception e){
            return ResultVo.fail("删除失败",e);  //包含了打印错误日志
        }
    }

}
